﻿using System;
using System.Data.Common;
using System.Data.SQLite;

namespace CommonUtils
{
    /// <summary>
    /// ADO.NET for Sqlite
    /// SQLite Expert
    /// http://www.sqliteexpert.com/download.html
    /// https://pc.qq.com/detail/16/detail_22776.html
    /// </summary>
    public class DbSqlite : DbBase
    {
        static DbSqlite _default;

        public static DbSqlite Default
        {
            get
            {
                if (_default == null)
                    _default = new DbSqlite(ConnectStrings.GetDefault());
                return _default;
            }
        }

        public class ConnectStrings
        {
            public const string Test = @"Data Source ='D:\Subversion\tools\Database\sqlite-test.db'";

            public static string FromPath(string path)
            => "Data Source =" + path.AddSingleQuotes();

            public static string Get(string path)
            => FromPath(path);

            /// <summary>
            /// EF会创建数据库，只需建好文件夹即可，copyFromCommonResources可以为false，不是EF框架保持true
            /// </summary>
            public static string GetDefault(bool copyFromCommonResources = true)
            {
                string path = PathConfig.DefaultSqlitePath;
                if (!FileUtil.Exists(path))
                {
                    if (copyFromCommonResources)
                        ResourceUtil.GetFromCommon(ResourceName.SqliteDb).CreateFile(path);
                    else
                        FileUtil.CreateFolder(path);
                }
                //LogUtil.PrintInfo(path);
                return FromPath(path);
            }
        }

        public DbSqlite(string connectString)
        : base(connectString) { }

        protected override DbConnection GetConnection()
        => new SQLiteConnection(ConnectString);

        protected override DbParameter GetParameter(string key, object value)
        => new SQLiteParameter(key, value);

        [Obsolete]
        protected override DbDataAdapter GetDataAdapter(DbCommand cmd)
        => throw new Exception("No SqliteDataAdapter");
    }
}
